package com.suse.interceptor;

import com.suse.common.util.core.BeanUtil;
import com.suse.common.util.core.StringUtil;
import com.suse.constant.RedisConstant;
import com.suse.model.vo.UserVo;
import com.suse.util.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 刷新Token拦截器
 * </p>
 *
 * @author 辜玉彬
 * @since 2022-10-22 14:13
 */
@Component
public class RefreshTokenInterceptor implements HandlerInterceptor {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.从请求头中获取 token
        String token = request.getHeader("authorization");
        if (StringUtil.isEmpty(token)) {
            return true;
        }
        // 2.通过 token 从 redis 中获取用户信息
        String userKey = RedisConstant.LOGIN_USER_PREFIX + token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(userKey);
        // 3.判断用户是否存在
        if (userMap.isEmpty()) {
            // 4.不存在，redis 中用户信息已过期
            return true;
        }
        // 5.存在，刷新 redis 中用户信息的过期时间
        stringRedisTemplate.expire(userKey, RedisConstant.LOGIN_USER_TTL, TimeUnit.MINUTES);
        // 6.保存用户到 ThreadLocal
        UserVo userVo = BeanUtil.fillBeanWithMap(userMap, new UserVo(), false);
        UserHolder.saveUser(userVo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
